#include "main.h"

#define BAUD   115200
#define BRT    (65536 - FOSC / BAUD / 4)
#define USE_ISP_CMD 1

// 34 78 55 a5 e2 c3 17 9c
code uint8_t recv_reset_list[8] = {0x34,0x78,0x55,0xa5,0xe2,0xc3,0x17,0x9c};
uint8_t recv_reset_num = 0;
static uint8_t *send_buf;
static uint8_t send_len = 0;
bit busy = 0;

void UartInit(void)
{
    P30 = 1;
    P31 = 1;
    P3M0 |= Bin(00000010);
    P3M0 &= ~Bin(00000001);
    P3M1 &= ~Bin(00000011);
    
	SCON = 0x50;		//8位数据,可变波特率
	AUXR |= 0x01;		//串口1选择定时器2为波特率发生器
	AUXR |= 0x04;		//定时器时钟1T模式
	T2L = BRT;		//设置定时初始值
	T2H = BRT>>8;		//设置定时初始值
	AUXR |= 0x10;		//定时器2开始计时
    
	ES = 1;
}

void UART1_Isr() interrupt 4
{
	if (RI)
	{
		RI = 0;                                 //清中断标志
#if USE_ISP_CMD
		if(SBUF == recv_reset_list[recv_reset_num])
		{
			recv_reset_num++;
			if(recv_reset_num >= 8)
				IAP_CONTR |= 0x60;
		}
		else if(SBUF == recv_reset_list[0])
            recv_reset_num = 1;
        else
			recv_reset_num = 0;
#endif
	}
	if(TI)
	{
		TI = 0;                                 //清中断标志
        if(send_len)
        {
            SBUF = *send_buf++;
            send_len--;
        }
        else
            busy = 0;
	}
}

#if 1
char putchar(char c)
{
	while(busy);
    SBUF = c;
    busy = 1;
	return c;
}
#endif

#if 0
void usrt_send_buf(uint8_t *buf, uint8_t len)
{
    send_buf = buf+1;
    send_len = len-1;
    SBUF = *buf;
    busy = 1;
}
#endif
